// handlers/category.go
package handlers

import (
	"encoding/json"
	"net/http"
	"strings"

	"zwai-app/config"
	"zwai-app/middleware"
	"zwai-app/services"
	"zwai-app/util"

	"go.mongodb.org/mongo-driver/bson/primitive"
)

func RegisterCategoryRoutes(mux *http.ServeMux, cfg config.Config) {
	mux.HandleFunc("/categories", middleware.AuthMiddleware(categoryListHandler, cfg))    // GET, POST
	mux.HandleFunc("/categories/", middleware.AuthMiddleware(categoryDetailHandler, cfg)) // PUT, DELETE
}

func categoryListHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case http.MethodGet:
		list, err := services.GetCategories(r.Context())
		if err != nil {
			util.JSONResponse(w, http.StatusInternalServerError, map[string]interface{}{"msg": err.Error()})
			return
		}
		util.JSONResponse(w, http.StatusOK, map[string]interface{}{"data": list})
	case http.MethodPost:
		var body struct {
			Name string `json:"name"`
		}
		if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
			util.JSONResponse(w, http.StatusBadRequest, map[string]interface{}{"msg": "参数错误"})
			return
		}
		id, err := services.CreateCategory(r.Context(), body.Name)
		if err != nil {
			util.JSONResponse(w, http.StatusInternalServerError, map[string]interface{}{"msg": err.Error()})
			return
		}
		util.JSONResponse(w, http.StatusOK, map[string]interface{}{"data": id.Hex()})
	default:
		util.JSONResponse(w, http.StatusMethodNotAllowed, nil)
	}
}

func categoryDetailHandler(w http.ResponseWriter, r *http.Request) {
	// URL: /categories/{id}
	parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
	if len(parts) != 2 {
		util.JSONResponse(w, http.StatusNotFound, nil)
		return
	}
	id, err := primitive.ObjectIDFromHex(parts[1])
	if err != nil {
		util.JSONResponse(w, http.StatusBadRequest, map[string]interface{}{"msg": "ID无效"})
		return
	}
	switch r.Method {
	case http.MethodPut:
		var body struct {
			Name string `json:"name"`
		}
		json.NewDecoder(r.Body).Decode(&body)
		err := services.UpdateCategory(r.Context(), id, body.Name)
		if err != nil {
			util.JSONResponse(w, http.StatusInternalServerError, map[string]interface{}{"msg": err.Error()})
			return
		}
		util.JSONResponse(w, http.StatusOK, nil)
	case http.MethodDelete:
		err := services.DeleteCategory(r.Context(), id)
		if err != nil {
			util.JSONResponse(w, http.StatusInternalServerError, map[string]interface{}{"msg": err.Error()})
			return
		}
		util.JSONResponse(w, http.StatusOK, nil)
	default:
		util.JSONResponse(w, http.StatusMethodNotAllowed, nil)
	}
}
